package cn.stylefeng.guns.modular.cb.service.impl;

import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.auth.model.LoginUser;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.cb.entity.CbCustomerStaff;
import cn.stylefeng.guns.modular.cb.mapper.CbCustomerStaffMapper;
import cn.stylefeng.guns.modular.cb.model.params.*;
import cn.stylefeng.guns.modular.cb.model.result.CbCustomerStaffResult;
import cn.stylefeng.guns.modular.cb.model.result.CbCustomerStudentsResult;
import cn.stylefeng.guns.modular.cb.model.result.CbObjectiveResult;
import cn.stylefeng.guns.modular.cb.model.result.CbPositionResult;
import cn.stylefeng.guns.modular.cb.service.*;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wj
 * @since 2021-01-07
 */
@Service
public class CbCustomerStaffServiceImpl extends ServiceImpl<CbCustomerStaffMapper, CbCustomerStaff> implements CbCustomerStaffService {

    private static Logger logger = LoggerFactory.getLogger(CbCustomerStaffServiceImpl.class);

    @Autowired
    private CbPositionService cbPositionService;

    @Autowired
    private CbMessagesService cbMessagesService;

    @Autowired
    private UserService userService;

    @Autowired
    private CbCustomerStudentsService cbCustomerStudentsService;

    @Autowired
    private CbFocusCollectionService cbFocusCollectionService;

    @Override
    public void add(CbCustomerStaffParam param){
        try{
            CbCustomerStaff entity = getEntity(param);
            if (entity.getAuth()==null){
                entity.setAuth(0);//没有发布简历的权限
            }
            if (entity.getStatus()!=null){
                entity.setStatus(1);//提交申请
            }
            entity.setUserStatus("ENABLE");
            entity.setContactSet(2);//手动获取联系方式
            this.save(entity);
            param.setId(entity.getId());
        }catch (Exception e){
            logger.error("add error: ", e);
        }
    }

    @Override
    public void addNew(CbCustomerStaffParam param) {
        try{
            //添加员工用户
            LoginUser user = LoginContextHolder.getContext().getUser();
            if (StringUtils.isEmpty(param.getStatus())){
                param.setStatus(1);//提交中，企业未通过
            }
            param.setPhone(user.getAccount());
            this.add(param);

            //添加职员用户角色
            this.userService.setRoles(user.getId(), String.valueOf(7));

            //员工添加后添加一条消息数据
            CbMessagesParam cbMessagesParam = new CbMessagesParam();
//        cbMessagesParam.setCreateUser(cbCustomerStaffParam.getId());
            //获取企业联系人
            cbMessagesParam.setMessageUserid(param.getCompanyId());
            cbMessagesParam.setSendUserid(param.getId());
            cbMessagesParam.setType(4L);
            cbMessagesParam.setMessage("您收到一条新的员工申请消息");
            cbMessagesParam.setStatus(0L);
            cbMessagesParam.setEventid(0L);
            cbMessagesService.add(cbMessagesParam);

            //添加成功后发送注册成功的消息
            CbMessagesParam messagesParam = new CbMessagesParam();
            messagesParam.setType(9L);
            messagesParam.setMessageUserid(param.getId());
            messagesParam.setMessage("恭喜注册成为会员，如果在使用上有什么问题可以进行反馈。");
            messagesParam.setStatus(0L);
            cbMessagesService.add(messagesParam);
        }catch (Exception e){
            logger.error("addNew error: ", e);
        }
    }

    @Override
    public void delete(CbCustomerStaffParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(CbCustomerStaffParam param){
        try{
            Long companyId = param.getCompanyId();
            CbCustomerStaff oldEntity = getOldEntity(param);
            Long oldCompanyId = oldEntity.getCompanyId();
            CbCustomerStaff newEntity = getEntity(param);
            ToolUtil.copyProperties(newEntity, oldEntity);
            //如果修改企业，需要给目标企业发送消息，并且删除权限
            if (!StringUtils.isEmpty(companyId) && !companyId.equals(oldCompanyId)){
                newEntity.setAuth(0);//删除权限
                newEntity.setStatus(1);//提交申请
                sendMsg(param);
            }else if (oldEntity.getStatus()!=2){//审批没有通过，再次提交
                newEntity.setStatus(1);//提交申请
                sendMsg(param);
            }
            this.updateById(newEntity);
        }catch (Exception e){
            logger.error("update error: ", e);
        }
    }

    @Override
    public CbCustomerStaffResult findBySpec(CbCustomerStaffParam param){
        return null;
    }

    @Override
    public List<CbCustomerStaffResult> findListBySpec(CbCustomerStaffParam param){
        return this.baseMapper.customList(param);
    }

    @Override
    public LayuiPageInfo findPageBySpec(CbCustomerStaffParam param){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    /**
     * 学生的校友-学长-全部
     * @param paramCondition
     * @return
     */
    @Override
    public LayuiPageInfo alumniByStaffList(CbCustomerStaffParam paramCondition) {
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.alumniByStaffList(pageContext, paramCondition);
        List<CbCustomerStaffResult> list = page.getRecords();
        try{
            for (CbCustomerStaffResult staff: list){
                List<CbPositionResult> positionList = cbPositionService.positionByLimit2(staff.getCompanyId());
                staff.setPositionList(positionList);
            }
        }catch (Exception e){
            logger.error("学生的校友 alumniByStaffList error: ", e);
        }

        page.setRecords(list);
        return LayuiPageFactory.createPageInfo(page);
    }

    /**
     * 根据求职意向查询 学生学长
     * @param list
     * @return
     */
//    public void getPositionByObjective(List<CbCustomerStaffResult> list){
//        LoginUser user = LoginContextHolder.getContext().getUser();
//        //获取求职意向
//        CbObjectiveParam objectiveParam = new CbObjectiveParam();
//        objectiveParam.setCreateUser(user.getId());
//        CbObjectiveResult objectiveResult = cbObjectiveService.findBySpec(objectiveParam);
//        String objectiveNature = objectiveResult.getNature();//职位性质
//        String objectiveProfessionalNo = objectiveResult.getProfessionalNo();//期望职位
//        String objectiveSalary = objectiveResult.getSalary();//期望薪资
//
//        for (CbCustomerStaffResult staff: list) {
////            List<CbPositionResult> positionList = cbPositionService.findListBySpec();
//        }
//
//    }

    /**
     * 获取职员信息
     * @param paramCondition
     * @return
     */
    @Override
    public CbCustomerStaffResult getStaff(CbCustomerStaffParam paramCondition) {
        CbCustomerStaffResult result = new CbCustomerStaffResult();
        try{
            result = this.baseMapper.getStaff(paramCondition);
        } catch (Exception e){
            logger.error("getStaff error:", e);
        }
        return result;
    }

    /**
     * 获取职员详情信息
     * @param paramCondition
     * @return
     */
    @Override
    public CbCustomerStaffResult getStaffDetail(CbCustomerStaffParam paramCondition) {
        CbCustomerStaffResult result = new CbCustomerStaffResult();
        try{
            result = this.baseMapper.getStaffDetail(paramCondition);
        } catch (Exception e){
            logger.error("getStaffDetail error:", e);
        }
        return result;
    }

    /**
     * 学生查询所有学长所在的公司
     * @param schoolNo
     * @return
     */
    @Override
    public List<CbCustomerStaffResult> companyByAlumni(String schoolNo) {
        return this.baseMapper.companyByAlumni(schoolNo);
    }


    /**
     * 删除员工所在企业
     * @param staffId
     * @return
     */
    @Override
    public int deleteStaffCompany(Long staffId) {
        return this.baseMapper.deleteStaffCompany(staffId);
    }

    /**
     * 员工数量统计
     * @return
     */
    @Override
    public List<Map<String,Object>> queryDateCount(String startDate, String[] countArr){
        return this.baseMapper.queryDateCount(startDate, countArr);
    }

    /**
     * 员工列表
     * @param paramCondition
     * @return
     */
    @Override
    public LayuiPageInfo staffList(CbCustomerStaffParam paramCondition) {
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.staffList(pageContext, paramCondition);
        return LayuiPageFactory.createPageInfo(page);
    }

    /**
     * 查看学长详情接口
     * @return
     */
    @Override
    public CbCustomerStaffResult staffDetail(CbCustomerStaffParam cbCustomerStaffParam) {
        LoginUser user = LoginContextHolder.getContext().getUser();
        CbCustomerStaffResult detail = new CbCustomerStaffResult();

        try{
            //学生信息
            CbCustomerStudentsParam studentParam = new CbCustomerStudentsParam();
            studentParam.setCreateUser(user.getId());
            CbCustomerStudentsResult studentsResult = cbCustomerStudentsService.getStudent(studentParam);

            //员工详情
            detail = this.getStaffDetail(cbCustomerStaffParam);

            //招聘列表
            CbPositionParam param = new CbPositionParam();
            param.setCompanyId(detail.getCompanyId());
            param.setType(1);//正在进行中的招聘
            List<CbPositionResult> list = this.cbPositionService.findListBySpec(param);
            detail.setPositionList(list);

            //是否关注
            CbFocusCollectionParam focusParam = new CbFocusCollectionParam();
            focusParam.setUserId(studentsResult.getId());
            focusParam.setObjectId(detail.getId());
            focusParam.setType(1);//关注
            Integer focus = cbFocusCollectionService.getFocusCollectionCount(focusParam);
            detail.setFocus(focus);

            //是否成功交换联系信息
            CbMessagesParam messagesParam = new CbMessagesParam();
            messagesParam.setCreateUser(user.getId());
            messagesParam.setMessageUserid(detail.getId());
            messagesParam.setType(3L);//交互联系方式
//            messagesParam.setEventid(1L);//同意
            Integer contact = cbMessagesService.getContactFlg(messagesParam);
            detail.setContact(contact);
        }catch (Exception e){
            logger.error("查看学长详情 staffDetail error: ", e);
        }
        return detail;
    }

    private Serializable getKey(CbCustomerStaffParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private CbCustomerStaff getOldEntity(CbCustomerStaffParam param) {
        return this.getById(getKey(param));
    }

    private CbCustomerStaff getEntity(CbCustomerStaffParam param) {
        CbCustomerStaff entity = new CbCustomerStaff();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

    /**
     * 加入企业，发生申请信息
     * @param cbCustomerStaffParam
     */
    public void sendMsg(CbCustomerStaffParam cbCustomerStaffParam){
        //员工添加后添加一条消息数据
        CbMessagesParam cbMessagesParam = new CbMessagesParam();
        //获取企业联系人
        cbMessagesParam.setMessageUserid(cbCustomerStaffParam.getCompanyId());
        cbMessagesParam.setSendUserid(cbCustomerStaffParam.getId());
        cbMessagesParam.setType(4L);
        cbMessagesParam.setMessage("您收到一条新的员工申请消息");
        cbMessagesParam.setStatus(0L);
        cbMessagesParam.setEventid(0L);
        cbMessagesService.add(cbMessagesParam);
    }
}
